/**
 * 
 */
package com.joinfun.rdsdk.mingdao.api.base;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author FMK
 * 2014年1月5日下午12:15:10
 *
 */
public class BaseRequest {
	public static HttpClient client;

	public static String request(String url, String method, Map<String, Object> params) {
		String resultString = null;
		if("POST".equalsIgnoreCase(method)) {
			HttpPost post = new HttpPost(url);
			Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			while(iterator.hasNext()) {
				Entry<String, Object> entry =  iterator.next();
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			try {
				post.setEntity(new UrlEncodedFormEntity(nvps));
				resultString = EntityUtils.toString(getClient().execute(post).getEntity());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				post.releaseConnection();
			}
		} else {
			StringBuffer sb = new StringBuffer(url);
			sb.append("?");
			Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
			while(iterator.hasNext()) {
				Entry<String, Object> entry =  iterator.next();
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			HttpGet get = new HttpGet(sb.toString());
			try {
				resultString = EntityUtils.toString(getClient().execute(get).getEntity());
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				get.releaseConnection();
			}
		}
		
		return resultString;
	}
	
	public static HttpClient getClient() {
		if(client == null) {
			client = HttpClients.createDefault();
		}
		return client;
	}
}
